package cn.zhf.shop.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.zhf.shop.entity.*;
import cn.zhf.shop.entity.lesson.Lesson;
import cn.zhf.shop.entity.organization.Organization;
import cn.zhf.shop.entity.search.ClassUserSearch;
import cn.zhf.shop.entity.search.OrderSearch;
import cn.zhf.shop.service.*;
import cn.zhf.shop.service.ShoppingOrderService;
import cn.zhf.shop.utils.OrderUtil;
import cn.zhf.shop.utils.UnionPay;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags = "订单模块")
@RequestMapping("/api/orders")
public class OrderController {

    @Resource
    private OrdersService ordersService;

    @Resource
    private CampusService campusService;

    @Resource
    private OrganizationService organizationService;

    @Resource
    private ShoppingService shoppingService;

    @Resource
    private LessonService lessonService;

    @Resource
    private ShoppingOrderService shoppingOrderService;

    @Resource
    private ClassUserService classUserService;

    @PostMapping("/")
    @ApiOperation(value = "插入订单")
    public Message<?> insertOrder(Orders o){
        int campusId = o.getCampus();
        Campus campus = campusService.getCampusById2(campusId);
        o.setCampusName(campus.getCampusName());
        int orgid = campus.getOrgId();
        Organization organization = organizationService.selectByPrimaryKey2(orgid);
        o.setOrgName(organization.getOrgName());
        o.setHead(campus.getHead());
        o.setReferenceId(organization.getReferenceId());
        return ordersService.insert(o);
    }

    @GetMapping("/order")
    @ApiOperation(value = "根据订单编号获取订单")
    public Message<Orders> getOrderByOrderId(String orderId){
        return ordersService.getByOrderId(orderId);
    }

    /**
     * 获取所有订单
     */
    @GetMapping("/all")
    @ApiOperation(value = "获取所有订单")
    public Message<List<Orders>> getAllOrders(){
        return ordersService.getAllOrders();
    }


    /**
     * 获取下单人用户编号
     */
    @GetMapping("/user")
    @ApiOperation(value = "根据下单人用户Id获取订单")
    public Message<List<Orders>> getOrdersByUserId(String userId){
        return ordersService.getByUserId(userId);
    }

    /**
     * 根据校区名获取订单
     */
    @GetMapping("/campus")
    @ApiOperation(value = "根据校区名称获取订单")
    public Message<List<Orders>> getOrdersByCampusName(String campusName){
        return ordersService.getByUserId(campusName);
    }

    /**
     * 根据订单状态获取订单
     */
    @GetMapping("/state")
    @ApiOperation(value = "根据订单状态获取订单")
    public Message<List<Orders>> getOrdersByCampusName(Integer state){
        return ordersService.getByState(state);
    }


    /**
     * 根据订单状态以及用户编号获取订单
     */
    @GetMapping("/state2")
    @ApiOperation(value = "根据订单状态以及用户编号获取订单")
    public Message<List<Orders>> getOrdersByUserIdAndState(String userId,Integer state){
        return ordersService.getByStateAndUserId(userId,state);
    }


    /**
     * 支付订单（微信小程序统一下单）
     */
    @PostMapping("/pay/wechat")
    @ApiOperation(value = "根据订单状态以及用户编号获取订单")
    public Message<?> getOrdersByUserIdAndState(String orderId) throws Exception {
        return ordersService.payOrder(orderId);
    }

    /**
     * 校验订单支付结果（向微信支付平台核验订单支付结果）
     */
    @PostMapping("/valid")
    @ApiOperation(value = "校验订单支付结果（向微信支付平台核验订单支付结果）")
    public Message<?> validOrder(String orderId){
        return ordersService.validOrder(orderId);
    }

    /**
     * 解析微信中心发来的支付结果
     */
    @PostMapping("/notify")
    @ApiOperation(value = "解析微信中心发来的支付结果")
    public String notify(HttpServletRequest req)throws Exception{
        return ordersService.resolveWeChatNotify(req);
    }

    /**
     * 更新订单支付状态
     */
    @GetMapping("/reference")
    @ApiOperation(value = "根据推荐人id查找订单")
    public Message<List<Orders>> getByReference(String reference)throws Exception{
        return ordersService.getByReference(reference);
    }

    @GetMapping("/org")
    @ApiOperation(value = "根据机构负责人id查找订单")
    public Message<List<Orders>> getByOrg(String head)throws Exception{
        return ordersService.getByOrg(head);
    }

    @GetMapping("/cam")
    @ApiOperation(value = "根据校区负责人id查找订单")
    public Message<List<Orders>> getByCam(String head)throws Exception{
        return ordersService.getByCam(head);
    }


    /**
     * H5微信支付统一下单
     */
    @PostMapping("/pay/H5")
    @ApiOperation(value = "H5微信支付统一下单")
    public Message<?> wxH5pay(String orderId,String userIp)throws Exception{
        return ordersService.wxH5pay(orderId,userIp);
    }

    /**
     * 购物车H5微信支付统一下单
     */
    @PostMapping("/pay/GH5")
    @ApiOperation(value = "购物车H5微信支付统一下单")
    public Message<?> wxH5payGou(ShoppingOrder shoppingOrder,String userIp)throws Exception{
        return ordersService.wxH5payGou(shoppingOrder,userIp);

    }



    /**
     * H5支付成功后接收微信通知
     */
    @GetMapping("/notify/H5")
    @ApiOperation(value = "H5支付成功后接收微信通知")
    public String notifyH5(HttpServletRequest req)throws Exception{
        return ordersService.resolveWeChatNotifyH5(req);
    }

    @PostMapping("/shopping/insertOrder")
    @ApiOperation(value = "购物车插入订单")
    public Message<ShoppingOrder> insertShopOrder(String str,String userName,String userIdCard,String userPhone){
        int[] arrays = new int[100];
        String orderIdStr="";
        if(str!=null){
            String[] str1 = str.split(";");
            for (int i=0;i<str1.length;i++){

                    arrays[i]= Integer.parseInt(str1[i]);

                    int shoppingId = arrays[i];
                    Shopping shopping = shoppingService.selectByPrimaryKey2(shoppingId);

                    String userId=shopping.getUserId();
                    int lessonId=shopping.getLessonId();
                    int lessonNum=shopping.getLessonNum();

                    Orders orders = new Orders();

                    orders.setLessonId(lessonId);
                    orders.setAmount(lessonNum);
                    orders.setUserId(userId);
                    orders.setUserIdCard(userIdCard);
                    orders.setUserName(userName);
                    orders.setUserPhone(userPhone);

                    Lesson lesson = lessonService.selectByPrimaryKey2(lessonId);
                    orders.setCampus(lesson.getCampus());

                    orders.setSinglePrice(new BigDecimal(lesson.getLessonPrice()));
                    orders.setTotalPrice(new BigDecimal(lesson.getLessonPrice()*lessonNum));

                    Campus campus = campusService.getCampusById2(lesson.getCampus());
                    orders.setCampusName(campus.getCampusName());
                    int orgid = campus.getOrgId();
                    Organization organization = organizationService.selectByPrimaryKey2(orgid);
                    orders.setOrgName(organization.getOrgName());

                    orders.setId(OrderUtil.genOrderId());
                    orderIdStr=orders.getId()+";"+orderIdStr;
                    orders.setCreateTime(new Date());
                    orders.setState(0);
                    orders.setHead(campus.getHead());
                    orders.setOrdersReceivingAddress(classUserService.selectByPrimaryKey(userId).getClassUserReceivingAddress());
                    ordersService.ShoppingOrderinsert(orders);
                    shoppingService.deleteByPrimaryKey(shoppingId);


             }
}
        ShoppingOrder shoppingOrder = new ShoppingOrder();
        shoppingOrder.setShoppingOrderId(OrderUtil.genOrderId());
        shoppingOrder.setOrderId(orderIdStr);
        shoppingOrder.setShoppingOrderStatus(0);
        shoppingOrder.setShoppingOrderPrice(new BigDecimal(0));
        shoppingOrderService.insertSelective(shoppingOrder);
        return Message.success("应该成功了吧").add(shoppingOrder);
    }

    /**
     * 银联支付接收短信通知
     */
    @PostMapping("/pay/UnionPaySSM")
    @ApiOperation(value = "银联支付接收短信通知")
    public Message<?> unionpayssm(String phoneNo,String txnAmt,String orderId){

         return ordersService.unionPaySSM(phoneNo,txnAmt,orderId);
    }

    /**
     * 银联支付或开通-直接付款
     */
    @PostMapping("/pay/UnionPay")
    @ApiOperation(value = "银联支付或开通-直接付款")
    public Message<?> unionpay(String aes) throws IOException {
        String s = "das1f561ef2cx16s";//String变量
        byte[] key = s.getBytes();//String转换为byte[]
        //构建Aes
        AES Aes = SecureUtil.aes(key);
        String string="";
        try {
            //
            byte[] decrypt = Aes.decrypt(aes);
            string= new String(decrypt);
            } catch (Exception exception) {
            exception.printStackTrace();
            return Message.fail("支付异常");
        }
        String[] str1 =string.split(";");

        return ordersService.unionPay(str1[3],str1[2],str1[0],str1[1]);
    }

    /**
     * 银联分期支付-直接付款
     */
    @PostMapping("/pay/UnionPayByStages")
    @ApiOperation(value = "银联分期支付-直接付款")
    public Message<?> payByStages(String aes) throws IOException {

        String s = "das1f561ef2cx16s";//String变量
        byte[] key = s.getBytes();//String转换为byte[]
        //构建Aes
        AES Aes = SecureUtil.aes(key);
        String string="";
        try {
            //
            byte[] decrypt = Aes.decrypt(aes);
            string= new String(decrypt);
        } catch (Exception exception) {
            exception.printStackTrace();
            return Message.fail("支付异常");
        }
        String[] str1 =string.split(";");

        return ordersService.payByStages(str1[3],str1[2],str1[0],str1[4],str1[1]);
    }

    /**
     * 银联支付或开通-购物车付款
     */
    @PostMapping("/pay/UnionPayShop")
    @ApiOperation(value = "银联支付或开通-购物车付款")
    public Message<?> unionpayShop(String aes) throws IOException {
        String s = "das1f561ef2cx16s";//String变量
        byte[] key = s.getBytes();//String转换为byte[]
        //构建Aes
        AES Aes = SecureUtil.aes(key);
        String string="";
        try {
            //
            byte[] decrypt = Aes.decrypt(aes);
            string= new String(decrypt);
        } catch (Exception exception) {
            exception.printStackTrace();
            return Message.fail("支付异常");
        }
        String[] str1 =string.split(";");

        return ordersService.unionpayShop(str1[3],str1[2],str1[0],str1[1]);
    }

    /**
     * 银联分期支付-购物车付款
     */
    @PostMapping("/pay/UnionPayByStagesShop")
    @ApiOperation(value = "银联分期支付-购物车付款")
    public Message<?> payByStagesShop(String aes) throws IOException {
        String s = "das1f561ef2cx16s";//String变量
        byte[] key = s.getBytes();//String转换为byte[]
        //构建Aes
        AES Aes = SecureUtil.aes(key);
        String string="";
        try {
            //
            byte[] decrypt = Aes.decrypt(aes);
            string= new String(decrypt);
        } catch (Exception exception) {
            exception.printStackTrace();
            return Message.fail("支付异常");
        }
        String[] str1 =string.split(";");


        return ordersService.payByStagesShop(str1[3],str1[2],str1[0],str1[4],str1[1]);
    }

    /**
     *  订单管理-精确查询
     */
    @PostMapping("/order/search1")
    @ApiOperation(value = "订单管理-精确查询")
    public Message<List<Orders>> search1(Integer lessonId,String orgName,String campusName,String userName,Integer userId){
        return ordersService.selectBySearch1(lessonId,orgName,campusName,userName,userId);
    }

    /**
     *  订单管理-模糊查询
     */
    @PostMapping("/order/search2")
    @ApiOperation(value = "订单管理-模糊查询")
    public Message<List<Orders>> search2(String str,Integer userId){
        return ordersService.slectBySearch2(str,userId);
    }


    @ApiOperation(value = "多条件组合模糊查询")
    @PostMapping("/mohu/condition/search")
    public Message mohuConditionSearch(OrderSearch c){
        return ordersService.mohuConditionSearch(c);
    }


    @ApiOperation(value = "根据id修改订单")
    @PutMapping("/id")
    public Message updateById(Orders orders){
        return ordersService.updateByPrimaryKeySelective(orders);
    }

}
